import React, { useEffect, useState } from 'react';
import {
  Form,
  Modal,
  Grid,
  Input,
  InputNumber,
  TimePicker,
  Select,
  Checkbox,
  Tree,
  Space,
} from '@arco-design/web-react';
import * as Model from '@/services/model';
import { routes } from '@/routes';
import useLocale from '@/utils/useLocale';
const { useForm } = Form;
const { Row, Col } = Grid;
interface DetailModalProps {
  roleInfo?: Model.Role.default | false;
  onCancel: () => void;
  onOk: (params: Model.Role.default) => void;
}

const menuList = routes;
const actionList = {
  insert: '新增',
  delete: '删除',
  update: '编辑',
  select: '查找',
  import: '导入',
  export: '导出',
};

export const DetailModal = (props: DetailModalProps) => {
  const [form] = useForm<Model.Role.default>();
  const [permissions, setPermissions] = useState([]);
  const locate = useLocale();
  useEffect(() => {
    if (props.roleInfo !== false) {
      form.setFieldsValue({
        ...props.roleInfo,
      });
    }
  }, [props.roleInfo]);

  const generateTreeData = (e) => {
    return {
      title: locate[e.name],
      key: e.key,
      children:
        e.children?.length > 0
          ? e.children.map((f) => generateTreeData(f))
          : Object.keys(actionList).map((f) => {
              return {
                title: actionList[f],
                key: e.key.toString() + '-' + f,
              };
            }),
    };
  };

  const submit = async () => {
    const res = await form.validate();
    console.log(res);
    if (res) {
      props.onOk({ ...res, permissions });
    }
  };
  return (
    <Modal
      visible={props.roleInfo !== false}
      title={`${props.roleInfo && props.roleInfo.id ? '修改' : '新增'}角色`}
      mountOnEnter
      unmountOnExit
      onCancel={props.onCancel}
      onOk={submit}
      alignCenter={false}
      okText="提交"
      cancelText="取消"
      style={{ width: 600 }}
    >
      <Form form={form} labelAlign="left">
        <Space>
          <Form.Item
            labelCol={{ flex: 'none', style: { width: 90 } }}
            wrapperCol={{ flex: 'none', style: { width: 200 } }}
            label="角色名："
            field="role"
            required
          >
            <Input placeholder="请输入角色名" allowClear />
          </Form.Item>
        </Space>
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item
              label="权限选择"
              field="permissions"
              trigger="onCheck"
              triggerPropName="checkedKeys"
              required
            >
              <Tree
                checkable
                defaultExpandedKeys={[]}
                treeData={menuList.map((e, i) => {
                  return generateTreeData(e);
                })}
              ></Tree>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
